/*
 * Copyright 2013 Pavel Stastny <pavel.stastny at gmail.com>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.aplikator.server.processes.impl.thread;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.aplikator.client.shared.descriptor.ProcessDTO;
import org.aplikator.server.processes.CannotCallStopException;
import org.aplikator.server.processes.ProcessPropeties;
import org.aplikator.server.processes.ProcessState;
import org.aplikator.server.processes.ProcessType;
import org.aplikator.server.processes.Work;

/**
 *
 * @author Pavel Stastny <pavel.stastny at gmail.com>
 */
public abstract class AbstractProcessThread implements org.aplikator.server.processes.Process {
 
    protected ExecutorService execService = Executors.newSingleThreadExecutor();

    protected Future<?> submited;

    protected String ident;
    protected String appname;

    protected Date startedDate;
    protected Date stoppedDate;
    
    
    protected ProcessPropeties processProperties = new ProcessPropeties();
    
    public AbstractProcessThread(String ident, String appname) {
         this.ident = ident;
         this.appname = appname;
    }

    @Override
    public String getIdentifier() {
        return this.ident;
    }



    @Override
    public void startMe() {
    	this.startedDate = new Date();
    	new _Thread(this.execService, getWork()).start();
    }

    
    @Override
    public void stopMe() throws CannotCallStopException {
        if (this.submited != null) {
        	this.stoppedDate = new Date();
            this.submited.cancel(true);
            
        } else {
            throw new CannotCallStopException("still not running");
        }
    }

    @Override
    public boolean isLiveProcess() {
        return ((!this.submited.isCancelled()) && (!this.submited.isDone()));
    }

    @Override
    public void redirectOutputStream(File f) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void redirectErrorStream(File f) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    

    @Override
    public ProcessType getType() {
        return ProcessType.THREAD;
    }

    @Override
    public ProcessState getProcessState() {
        if (submited != null) {
            if (submited.isCancelled()) return ProcessState.KILLED;
            if (submited.isDone())  return ProcessState.FINISHED;
            return ProcessState.RUNNING;
        } else {
            return ProcessState.FAILED;
        }
    }

    @Override
    public String getApplicationName() {
        return this.appname;
    }

    @Override
    public void updateProcessIntrnalState(Object value) {
        
    }
    
    protected abstract Runnable getWork();

    @Override
    public ProcessPropeties getProcessProperties() {
        return this.processProperties;
    }

    @Override
    public ProcessDTO toProcessDTO() {
        ProcessDTO pdto = new ProcessDTO();
        
        if (this.startedDate !=  null) pdto.setStartedDate(FORMAT.format(this.startedDate));
        if (this.stoppedDate != null) pdto.setStoppedDate(FORMAT.format(this.stoppedDate));

        pdto.setIdentifier(this.getIdentifier());
        pdto.setProcessType(this.getType().name());
        pdto.setLiveProcess(this.isLiveProcess());
        pdto.setProcessState(getProcessState().name());
        pdto.setProcessProperties(getProcessProperties().toMap());
        
        return pdto;
    }
    
    
    @Override
	public Date getStartedDate() {
    	return this.startedDate;
    }

	@Override
	public Date getStoppedDate() {
		return this.stoppedDate;
	}




	class _Thread extends Thread {
        
        private ExecutorService execService = null;
        private Runnable work;
        
        public _Thread(ExecutorService execService, Runnable work) {
            this.execService = execService;
            this.work = work;
        }
        
        @Override
        public void run() {
            AbstractProcessThread.this.submited = execService.submit(this.work);
            execService.shutdown();
        }
    }
}
